package com.richman.view;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Vector;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

import com.richman.controller.DecreaseRatioClient;

import java.awt.Component;

import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class PS38AccountPane extends JPanel {
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 2L;
	
	public Vector<Object[]> showitemVec = null;
	
	
	MyTableModel tableMode = null; 
	
	JTable table = null;
	
	public PS38AccountPane() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel panel = new JPanel();
		add(panel, BorderLayout.NORTH);
		panel.setPreferredSize(new Dimension(0, 50));
		panel.setLayout(null);
		
		JButton addButton = new JButton("添加账号");
		addButton.setBounds(722, 10, 117, 30);
		panel.add(addButton);
		
		JButton saveButton = new JButton("保存设置");
		saveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				
				if(checkEngineStart()) {
            		return;
            	}
				
				
				updateAccountsList();
				
				JOptionPane.showMessageDialog(null, "修改成功", "修改成功", JOptionPane.DEFAULT_OPTION);
				
			}
		});
		saveButton.setBounds(886, 10, 117, 30);
		panel.add(saveButton);
		
		tableMode = new MyTableModel();  
		table = new JTable(tableMode); 
		showitemVec = new Vector<Object[]>();
		
		
		
        addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if(checkEngineStart()) {
            		return;
            	}
				
				
				Object [] objdata = new Object[6];
		        objdata[0] = false;
		        objdata[1] = "https://www.ps3838.com/";
		        objdata[2] = "双击输入";
		        objdata[3] = "双击输入";
		        objdata[4] = "---";
		        
		        objdata[5] = "---";
		        
		        objdata[6] = "删除";
		        showitemVec.add(objdata);
		        
		        
		        
		        tableMode.updateTable();
			}
		});
		
		
		
		
		
		
		
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane, BorderLayout.CENTER);
		
		
		
		
		//talbe init
		table.getColumnModel().getColumn(0).setPreferredWidth(20);//
        table.getColumnModel().getColumn(1).setPreferredWidth(100);//
	    table.getColumnModel().getColumn(2).setPreferredWidth(80);//
	    table.getColumnModel().getColumn(3).setPreferredWidth(80);//
	    table.getColumnModel().getColumn(4).setPreferredWidth(30);//
	    table.getColumnModel().getColumn(0).setCellEditor(new CheckBoxCellEditor());
        table.getColumnModel().getColumn(0).setCellRenderer(new CWCheckBoxRenderer());
	    
	    table.setRowHeight(30);
	    table.setFont(new java.awt.Font("微软雅黑", Font.PLAIN, 13));
	    DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
        tcr.setHorizontalAlignment(JLabel.CENTER);
        
        table.setDefaultRenderer(Object.class, tcr);
        table.addMouseListener(new MouseAdapter(){//设置鼠标点击响应
            public void mouseClicked(MouseEvent e){
            	
            	
            	if(checkEngineStart()) {
            		return;
            	}
            	
            	
            	int columnIndex = table.columnAtPoint(e.getPoint()); //获取点击的列
                int rowIndex = table.rowAtPoint(e.getPoint()); //获取点击的行
                
                
                
                if(columnIndex == 5) { //删除账号
                	int n = JOptionPane.showConfirmDialog(null, "确认删除吗?", "删除账号", JOptionPane.YES_NO_OPTION);
    				if (n == JOptionPane.YES_OPTION) {

	            		showitemVec.remove(rowIndex);
	            		tableMode.updateTable();
	            		//updateAccountsList();
    				}
                }
                
                if(e.getClickCount() == 1){ //单击自动登录
                    if(columnIndex == 0) {//第0列时，执行代码
                        if(table.getValueAt(rowIndex,columnIndex) == null){ //如果未初始化，则设置为false
                        	table.setValueAt(false, rowIndex, columnIndex);
                          }

                        if(((Boolean)table.getValueAt(rowIndex,columnIndex)).booleanValue()){ //原来选中
                        	showitemVec.elementAt(rowIndex)[columnIndex] = false;
                        	showitemVec.elementAt(rowIndex)[4] = "---";

                        	tableMode.updateTable();
                        	//updateAccountsList();
                          }
                        else {//原来未选中
                        	showitemVec.elementAt(rowIndex)[columnIndex] = true;
                        	
                        	
                        	tableMode.updateTable();
                        	//updateAccountsList();
                          }
                     } 
                }
	               	
            }
        });
        //end table init
        
        //设置窗口大小
        setBounds(100, 100, 1600, 800); 
        
        readAccountsList();
		
		
		
		
		
		
		
		
	}
	
	
	
	
	
	public boolean checkEngineStart() {
		if(DecreaseRatioClient.bStartEngine == true) {
    		JOptionPane.showMessageDialog(null, "如需修改账号，请先停止抓取", "错误", JOptionPane.ERROR_MESSAGE);
    		return true;
    	}
		return false;
	}
	
	
	
	
	
	public void updateAccountsList() {		
		try{	
			File file = new File("account/" + "ps38accountslist.txt");

			if(!file.exists()){	
				file.createNewFile();
			}
			
			BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));

			String str = "";
			for(Object [] obs : showitemVec) {
				str = obs[0] + "," + obs[1] + "," + obs[2] + "," + obs[3];
				fwlocal.append(str);
				fwlocal.newLine();
				fwlocal.flush();
			}

			fwlocal.close();
	
		}catch(FileNotFoundException e) {
			e.printStackTrace();
			return;
		} catch(IOException e) {
			e.printStackTrace();
			return;
		}
	}
	
	
	
	
	
	/**
	 * 读取账号列表文件
	 */
	private void readAccountsList() {
		File file = new File("account/" + "ps38accountslist.txt");
		
		if(!file.exists()) {
			System.out.println("[readAccountsList] 文件不存在");
			return;
		}
		
		BufferedReader freader = null;
		try {
			freader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			
			String str = "";
			while ((str = freader.readLine()) != null) {
				String[] contents = str.split(",");
				if(contents.length == 4){
					Object [] objdata = new Object[16];
					Boolean b = Boolean.parseBoolean(contents[0]);
			        objdata[0] = b;
			        objdata[1] = contents[1];
			        objdata[2] = contents[2];
			        objdata[3] = contents[3];
			        objdata[4] =  "---";
			        objdata[5] =  "---";
			        objdata[6] = "删除";
			        showitemVec.add(objdata);
	        
				}
			}
			
			freader.close();
		} catch(FileNotFoundException e) {
			e.printStackTrace();
			return;
		} catch(IOException e) {
			e.printStackTrace();
			return;
		}
					
	}
	
	
	
	
	
	
	
	
	
	
	/**
	 * 
	 * TableModel类
	 *
	 */
	public class MyTableModel extends AbstractTableModel  
    {  
        /**
		 * 
		 */
		private static final long serialVersionUID = 1001L;

        String[] columnNames =  
        	 { "使用", "网址", "账号", "密码", "状态", "余额", "删除账号"};
        

        /** 
         * 得到数据所对应对象 
         */  
        @Override  
        public Object getValueAt(int rowIndex, int columnIndex)  
        {  	
        	try{
        			return showitemVec.elementAt(rowIndex)[columnIndex];  		
        	}catch(Exception e){
        		e.printStackTrace();
        		return null;
        	}
	
        }      
  
  
        /** 
         * 构造方法，初始化二维数组data对应的数据 
         */  
        public MyTableModel()  
        {  

        }  
  
        // 以下为继承自AbstractTableModle的方法，可以自定义  
        /** 
         * 得到列名 
         */  
        @Override  
        public String getColumnName(int column)  
        {  
            return columnNames[column];  
        }  
          
        /** 
         * 重写方法，得到表格列数 
         */  
        @Override  
        public int getColumnCount()  
        {  
            return columnNames.length;  
        }  
  
        /** 
         * 得到表格行数 
         */  
        @Override  
        public int getRowCount()  
        {         
	        if(null == showitemVec){
	    		return 0;
	    	}
	        
	        //System.out.println(gameDetailsVec.size());
	        
            return showitemVec.size();  
        }  
  
        /** 
         * 得到指定列的数据类型 
         */  
        @Override  
        public Class<?> getColumnClass(int columnIndex)  
        {  
            return String.class;
        }  
  
        /** 
         *设置可否编辑
         */  
        @Override  
        public boolean isCellEditable(int rowIndex, int columnIndex)  
        {  
        	if(columnIndex == 1 || columnIndex == 2 || columnIndex == 3) {
        		return true;
        	}
            return false;
        }  
          
        /** 
         * 如果数据单元为可编辑，则将编辑后的值替换原来的值 
         */  
        @Override  
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)  
        {  
        	showitemVec.elementAt(rowIndex)[columnIndex] = aValue;
        	fireTableCellUpdated(rowIndex, columnIndex);
        	
//        	if(columnIndex == 0) { //登录信息是否改变
//        		updateAccountsList();
//        	} else if(columnIndex <= 3) {
//        	}
            /*detailsData.elementAt(rowIndex)[columnIndex] = (String)aValue;  
            通知监听器数据单元数据已经改变  
            fireTableCellUpdated(rowIndex, columnIndex);  */
        }  
        
        public void updateTable(){
        	fireTableDataChanged();
        }
        
        public void updateTableCell(int rowIndex, int columnIndex){
        	fireTableCellUpdated(rowIndex, columnIndex);
        }
        
    }  //end class MyTableModel 
	
	/**
	 * 
	 * inner class 单选框
	 *
	 */
	class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor {
	 
	  private static final long serialVersionUID = 1002L;

	  
	  protected JCheckBox checkBox;

	 
	  public CheckBoxCellEditor() {
	    checkBox = new JCheckBox();
	    checkBox.setHorizontalAlignment(SwingConstants.CENTER);
	    // checkBox.setBackground( Color.white);
	  }

	  
	  @Override 
	  public Object getCellEditorValue() {
	    return Boolean.valueOf(checkBox.isSelected());
	  }

	
	  @Override 
	  public Component getTableCellEditorComponent(
	    JTable  table,
	    Object  value,
	    boolean isSelected,
	    int     row,
	    int     column) {
	    checkBox.setSelected(((Boolean) value).booleanValue());

	    return checkBox;

	  }
	} // end inner class CheckBoxCellEditor

	/**
	 * 
	 * inner class CWCheckBoxRenderer
	 *
	 */
	class CWCheckBoxRenderer extends JCheckBox implements TableCellRenderer {
	  
	  private static final long serialVersionUID = 1003L;
	  
	  Border border = new EmptyBorder(1, 2, 1, 2);

	  public CWCheckBoxRenderer() {
	    super();
	    setOpaque(true);
	    setHorizontalAlignment(SwingConstants.CENTER);
	  }

	  @Override 
	  public Component getTableCellRendererComponent(
	    JTable  table,
	    Object  value,
	    boolean isSelected,
	    boolean hasFocus,
	    int     row,
	    int     column) {
	    if (value instanceof Boolean) {
	      setSelected(((Boolean) value).booleanValue());

	      // setEnabled(table.isCellEditable(row, column));
	      setForeground(table.getForeground());
	      setBackground(table.getBackground());

	    }

	    return this;
	  }
	} // end inner class CWCheckBoxRenderer

	public Vector<String[]> getPS38Accounts() {
		
		Vector<String[]> accounts = new Vector<String[]>();
		
		for(int i = 0; i < showitemVec.size(); i++) {
			if((Boolean)(showitemVec.elementAt(i)[0])) {
				String[] account = {(String)(showitemVec.elementAt(i)[1]), (String)(showitemVec.elementAt(i)[2]), (String)(showitemVec.elementAt(i)[3])};
				accounts.add(account);
			}
		}
		
		
		return accounts;
	}










	//-1 最初状态  ,  0 prepareLogin成功, 1 get main page success, 2 登录成功, -2 登录失败,  3抓取成功, -3抓取失败
	public void updateAccoutStatus(String account, int statusCode) {
		SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm:ss");// 设置日期格式
		String time = df.format(System.currentTimeMillis());
		
		
		if(account != null) {
			
			for(int i = 0 ; i < showitemVec.size(); i++) {
				
				String localAccount = (String)showitemVec.elementAt(i)[2];
				
				if(localAccount.equals(account)) {
					
					if(statusCode == -1) {
						showitemVec.elementAt(i)[4] = time + " 无法登录";
					}else if(statusCode == 0 || statusCode == 1) {
						showitemVec.elementAt(i)[4] = time + " 登录中";
					}else if(statusCode == 2) {
						showitemVec.elementAt(i)[4] = time + " 登录成功";
					}else if(statusCode == -2) {
						showitemVec.elementAt(i)[4] = time + "  登录失败";
					}else if(statusCode == 3) {
						showitemVec.elementAt(i)[4] = time + " 获取赛事列表成功";
					}else if(statusCode == -3) {
						showitemVec.elementAt(i)[4] = time + " 获取赛事列表失败";
					}
					
					
					tableMode.updateTable();
					
					
					break;
					
				}
				
			}
			
		}
	}
	
	
	public void updateAccountBalance(String account, String balance) {
		
		if(account != null) {
			
			for(int i = 0 ; i < showitemVec.size(); i++) {
				
				String localAccount = (String)showitemVec.elementAt(i)[2];
				
				if(localAccount.equals(account)) {
					
					
					showitemVec.elementAt(i)[5] = balance;
					
					
					
					tableMode.updateTable();
					
					
					break;
					
				}
				
			}
			
		}
		
	}
	

}
